/**
 * @ClassName LC21
 * 合并两个有序链表
 * @Author ykx
 * @Date 2024/3/1 22:38
 * @Version 1.0
 */
public class LC21 {
    public static void main(String[] args) {
        LC21 lc21 = new LC21();
        int[] nums1 = {1, 2, 4};
        int[] nums2 = {1, 3, 4};
        ListNode list1 = ListNode.setData(nums1);
        ListNode list2 = ListNode.setData(nums2);
        System.out.println(lc21.mergeTwoLists(list1, list2));
    }

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode pre = new ListNode(-1);
        ListNode result = pre;
        while (list1 != null && list2 != null) {
            if (list1.val > list2.val) {
                pre.next = new ListNode(list2.val);
                pre = pre.next;
                list2 = list2.next;
            } else {
                pre.next = new ListNode(list1.val);
                pre = pre.next;
                list1 = list1.next;
            }
        }

        while (list1 != null) {
            pre.next = new ListNode(list1.val);
            pre = pre.next;
            list1 = list1.next;
        }

        while (list2 != null) {
            pre.next = new ListNode(list2.val);
            pre = pre.next;
            list2 = list2.next;
        }

        return result.next;
    }
}
